﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<style>
    .form-container {
        padding: 20px;
        background: #fff;
    }

    .form-row {
        display: flex;
        margin-bottom: 15px;
        align-items: center;
    }

        .form-row .layui-form-label {
            width: 120px;
            text-align: right;
            padding-right: 10px;
        }

        .form-row .layui-input-block {
            margin-left: 130px;
        }

    .layui-textarea {
        resize: vertical;
        min-height: 100px;
    }

    .btn-group {
        text-align: center;
        margin-top: 30px;
    }

    .input-with-addon {
        display: flex;
        align-items: center;
        gap: 10px;
    }

        .input-with-addon .layui-input {
            flex: 1;
        }

        .input-with-addon .addon-item {
            flex-shrink: 0;
        }
    
    .loading {
        text-align: center;
        padding: 50px;
        color: #999;
    }
</style>
<link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
<body>
    <div class="loading" id="loadingDiv">
        <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
        正在加载数据...
    </div>
    
    <div class="form-container" id="formContainer" style="display: none;">
        <form class="layui-form" lay-filter="updateSalesReturnForm">
            <!-- 隐藏字段存储ID -->
            <input type="hidden" name="Id" id="salesReturnId">
            
            <div class="form-row">
                <label class="layui-form-label"><span style="color: red;">*</span>退货单编号:</label>
                <div class="layui-input-block">
                    <div class="input-with-addon">
                        <input type="text" name="ReturnNumber" placeholder="请输入退货单编号" autocomplete="off" class="layui-input" lay-verify="required">
                        <div class="addon-item">
                            <input type="checkbox" name="autoGenerate" title="自动生成" lay-skin="primary">
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-row">
                <label class="layui-form-label"><span style="color: red;">*</span>退货单名称:</label>
                <div class="layui-input-block">
                    <input type="text" name="ReturnName" placeholder="请输入退货单名称" autocomplete="off" class="layui-input" lay-verify="required">
                </div>
            </div>

            <div class="form-row">
                <label class="layui-form-label">销售订单编号:</label>
                <div class="layui-input-block">
                    <div class="input-with-addon">
                        <input type="text" name="SalesOrdersCode" placeholder="请输入销售订单编号" autocomplete="off" class="layui-input">
                        <div class="addon-item">
                            <input type="checkbox" name="autoGenerateSales" title="自动生成" lay-skin="primary">
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-row">
                <label class="layui-form-label">客户编号:</label>
                <div class="layui-input-block">
                    <div class="input-with-addon">
                        <input type="text" name="CustomeCode" placeholder="请输入客户编码" autocomplete="off" class="layui-input">
                        <div class="addon-item">
                            <button type="button" class="layui-btn layui-btn-sm" onclick="selectCustomer()">
                                <i class="layui-icon layui-icon-search"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-row">
                <label class="layui-form-label"><span style="color: red;">*</span>客户名称:</label>
                <div class="layui-input-block">
                    <input type="text" name="CustomeName" placeholder="请输入客户名称" autocomplete="off" class="layui-input" lay-verify="required">
                </div>
            </div>

            <div class="form-row">
                <label class="layui-form-label"><span style="color: red;">*</span>退货日期:</label>
                <div class="layui-input-block">
                    <input type="text" name="ReturnDate" id="returnDate" placeholder="请选择退货日期" autocomplete="off" class="layui-input" lay-verify="required" readonly>
                </div>
            </div>

            <div class="form-row">
                <label class="layui-form-label">退货仓库:</label>
                <div class="layui-input-block">
                    <select name="ReturnsWarehouse" lay-verify="required" lay-search="">
                        <option value="">请选择退货仓库</option>
                        <option value="成品仓库">成品仓库</option>
                        <option value="原料仓库">原料仓库</option>
                        <option value="半成品仓库">半成品仓库</option>
                        <option value="备件仓库">备件仓库</option>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <label class="layui-form-label">单据状态:</label>
                <div class="layui-input-block">
                    <select name="DocumentStatus" lay-verify="required" disabled>
                        <option value="">请选择单据状态</option>
                        <option value="1">草稿</option>
                        <option value="2">已确认</option>
                        <option value="3">审核中</option>
                        <option value="4">已审批</option>
                        <option value="5">已完成</option>
                        <option value="6">已拒绝</option>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <label class="layui-form-label"><span style="color: red;">*</span>退货原因:</label>
                <div class="layui-input-block">
                    <textarea name="ReasonReturn" placeholder="请输入退货原因" class="layui-textarea" lay-verify="required"></textarea>
                </div>
            </div>

            <div class="btn-group">
                <button type="submit" class="layui-btn" lay-submit lay-filter="submitForm">更新</button>
                <button type="button" class="layui-btn layui-btn-primary" onclick="closeModal()">取消</button>
            </div>
        </form>
    </div>
</body>
<script src="~/scripts/jquery-3.4.1.min.js"></script>
<script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
<script>
    layui.use(['form', 'laydate', 'layer'], function(){
        var form = layui.form;
        var laydate = layui.laydate;
        var layer = layui.layer;
        
        var currentData = null; // 存储当前编辑的数据

        // 初始化日期选择器
        laydate.render({
            elem: '#returnDate',
            type: 'date',
            max: 0
        });

        // 页面初始化
        $(document).ready(function(){
            // 获取URL参数中的ID
            var urlParams = new URLSearchParams(window.location.search);
            var id = urlParams.get('id');
            
            if (id) {
                loadSalesReturnData(id);
            } else {
                // 如果没有ID，显示错误
                $('#loadingDiv').html('<i class="layui-icon layui-icon-close" style="color: red;"></i> 未找到要编辑的记录');
            }
        });

        // 加载销售退货数据
        function loadSalesReturnData(id) {
            $.ajax({
                url: '/Warehousings/FindSalesReturns',
                type: 'GET',
                data: { id: id },
                success: function(response) {
                    console.log('Load data response:', response);
                    
                    if (response && response.length > 0) {
                        currentData = response[0]; // 取第一条记录
                        fillFormData(currentData);
                        $('#loadingDiv').hide();
                        $('#formContainer').show();
                    } else {
                        $('#loadingDiv').html('<i class="layui-icon layui-icon-close" style="color: red;"></i> 未找到指定的销售退货记录');
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading data:', error);
                    $('#loadingDiv').html('<i class="layui-icon layui-icon-close" style="color: red;"></i> 加载数据失败: ' + error);
                }
            });
        }

        // 填充表单数据
        function fillFormData(data) {
            // 填充基本字段
            $('#salesReturnId').val(data.id);
            $('input[name="ReturnNumber"]').val(data.returnNumber || '');
            $('input[name="ReturnName"]').val(data.returnName || '');
            $('input[name="SalesOrdersCode"]').val(data.salesOrdersCode || '');
            $('input[name="CustomeCode"]').val(data.customeCode || '');
            $('input[name="CustomeName"]').val(data.customeName || '');
            $('textarea[name="ReasonReturn"]').val(data.reasonReturn || '');
            
            // 处理退货日期
            if (data.returnDate) {
                try {
                    var date = new Date(data.returnDate);
                    var formattedDate = date.getFullYear() + '-' + 
                                      String(date.getMonth() + 1).padStart(2, '0') + '-' + 
                                      String(date.getDate()).padStart(2, '0');
                    $('input[name="ReturnDate"]').val(formattedDate);
                } catch(e) {
                    console.error('Date parsing error:', e);
                }
            }
            
            // 设置下拉框值
            $('select[name="ReturnsWarehouse"]').val(data.returnsWarehouse || '');
            $('select[name="DocumentStatus"]').val(data.documentStatus || '1');
            
            // 由于已有数据，取消自动生成选项
            $('input[name="autoGenerate"]').prop('checked', false);
            $('input[name="autoGenerateSales"]').prop('checked', false);
            
            // 重新渲染表单
            form.render();
        }

        // 生成退货单编号
        function generateReturnNumber() {
            var now = new Date();
            var year = now.getFullYear();
            var month = String(now.getMonth() + 1).padStart(2, '0');
            var day = String(now.getDate()).padStart(2, '0');
            var hours = String(now.getHours()).padStart(2, '0');
            var minutes = String(now.getMinutes()).padStart(2, '0');
            var seconds = String(now.getSeconds()).padStart(2, '0');

            return 'SR' + year + month + day + hours + minutes + seconds;
        }

        // 生成销售订单编号
        function generateSalesOrderNumber() {
            var now = new Date();
            var year = now.getFullYear();
            var month = String(now.getMonth() + 1).padStart(2, '0');
            var day = String(now.getDate()).padStart(2, '0');
            var hours = String(now.getHours()).padStart(2, '0');
            var minutes = String(now.getMinutes()).padStart(2, '0');
            var seconds = String(now.getSeconds()).padStart(2, '0');
            var milliseconds = String(now.getMilliseconds()).padStart(3, '0');

            return 'SO' + year + month + day + hours + minutes + seconds + milliseconds.substring(0, 2);
        }

        // 自动生成开关控制
        form.on('checkbox()', function(data){
            if(data.elem.name === 'autoGenerate') {
                var returnNumberInput = $('input[name="ReturnNumber"]');

                if(data.elem.checked) {
                    // 打开自动生成
                    returnNumberInput.val(generateReturnNumber());
                    returnNumberInput.attr('readonly', true);
                } else {
                    // 关闭自动生成 - 手动输入
                    if (!currentData || !currentData.returnNumber) {
                        returnNumberInput.val('');
                    }
                    returnNumberInput.removeAttr('readonly');
                    returnNumberInput.focus();
                }
            }

            if(data.elem.name === 'autoGenerateSales') {
                var salesOrderInput = $('input[name="SalesOrdersCode"]');

                if(data.elem.checked) {
                    // 打开自动生成
                    salesOrderInput.val(generateSalesOrderNumber());
                    salesOrderInput.attr('readonly', true);
                } else {
                    // 关闭自动生成 - 手动输入
                    if (!currentData || !currentData.salesOrdersCode) {
                        salesOrderInput.val('');
                    }
                    salesOrderInput.removeAttr('readonly');
                    salesOrderInput.focus();
                }
            }
        });

        // 表单提交
        form.on('submit(submitForm)', function(data){
            var field = data.field;

            // 确保ID存在
            if (!field.Id) {
                layer.msg('缺少记录ID，无法更新', {icon: 2});
                return false;
            }

            // 转换日期格式
            if(field.ReturnDate) {
                field.ReturnDate = new Date(field.ReturnDate).toISOString();
            }

            // 转换数值类型
            field.DocumentStatus = parseInt(field.DocumentStatus) || 1;

            // 提交更新数据
            $.ajax({
                url: '/Warehousings/UpdateSalesReturns',
                type: 'POST',
                data: field,
                success: function(res) {
                    if(res === 1) {
                        // 准备更新后的数据
                        var updatedData = {
                            id: field.Id,
                            returnNumber: field.ReturnNumber,
                            returnName: field.ReturnName,
                            salesOrdersCode: field.SalesOrdersCode,
                            customeCode: field.CustomeCode,
                            customeName: field.CustomeName,
                            returnDate: field.ReturnDate,
                            returnsWarehouse: field.ReturnsWarehouse,
                            documentStatus: field.DocumentStatus,
                            reasonReturn: field.ReasonReturn
                        };

                        layer.msg('更新成功', {icon: 1}, function(){
                            // 通知父页面更新对应行的数据，而不是重新加载整个列表
                            if (parent && parent.updateTableRow) {
                                parent.updateTableRow(updatedData);
                            }
                            
                            var index = parent.layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                        });
                    } else {
                        layer.msg('更新失败', {icon: 2});
                    }
                },
                error: function(xhr, status, error) {
                    layer.msg('网络错误: ' + error, {icon: 2});
                    console.error('Update error:', xhr.responseText);
                }
            });

            return false;
        });

        // 选择客户
        window.selectCustomer = function() {
            layer.open({
                type: 2,
                title: '选择客户',
                shadeClose: true,
                shade: 0.3,
                maxmin: true,
                area: ['80%', '70%'],
                content: '/Warehousings/ShowUserView',
                success: function(layero, index) {
                    console.log('客户选择弹窗已打开');
                }
            });
        };

        // 设置客户信息（供子窗口调用）
        window.setCustomerInfo = function(customerId, customerName) {
            $('input[name="CustomeCode"]').val(customerId);
            $('input[name="CustomeName"]').val(customerName);
            layer.msg('客户信息已设置', {icon: 1});
        };

        // 关闭模态框
        window.closeModal = function() {
            var index = parent.layer.getFrameIndex(window.name);
            parent.layer.close(index);
        };
    });
</script>
